//
//  KSTableView.m
//  BasketBallLeagues
//
//  Created by kenshin on 4/25/17.
//  Copyright © 2017 kenshin. All rights reserved.
//

#import "KSTableView.h"

@interface KSTableView ()

@property (nonatomic, strong) NSMutableArray *dataItems;
@property (nonatomic, assign) NSUInteger currentPage;

@end

@implementation KSTableView


- (void)dealloc
{
    [self stopRequest];
}

- (void)setPagingListDelegate:(id<KSListViewDelegate>)pagingListDelegate
{
    _pagingListDelegate = pagingListDelegate;
    self.dataSource = pagingListDelegate;
    self.delegate = pagingListDelegate;
    [self setHeaderRefreshing];
}

- (void)setPagingListDataSource:(id<KSListViewDataSource>)pagingListDataSource
{
    _pagingListDataSource = pagingListDataSource;
    NSArray *items = [self firstPageDataCache];
    if (items && items.count > 0) {
        self.dataItems = [NSMutableArray arrayWithArray:items];
    } else {
        self.dataItems = [NSMutableArray array];
    }
}

/// 请求第一页数据
- (void)requestFirstPageData
{
    [self stopRequest];
    self.currentPage = 0;
    __weak typeof(self) weakSelf = self;
    [self startRequestCompletion:^(NSArray *dataItems, NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            [strongSelf endRefreshing];
            [strongSelf hideErrorView];
            if (error) {
                if (strongSelf.dataItems.count == 0) {
                    [strongSelf showErrorView:error];
                } else {
                    [strongSelf showErrorToast:error];
                }
                [strongSelf reloadData:YES];
                return;
            }
            
            [strongSelf.dataItems removeAllObjects];
            if (dataItems.count == 0) {
                [strongSelf endRefreshingWithNoMoreData];
            } else {
                [strongSelf.dataItems addObjectsFromArray:dataItems];
                [strongSelf saveFirstPageDataToCache];
                
                if ([strongSelf.pagingListDataSource respondsToSelector:@selector(minItemCountOfTryToLoadMoreData)]) {
                    if (strongSelf.dataItems.count > [strongSelf.pagingListDataSource minItemCountOfTryToLoadMoreData]) {
                        [strongSelf setFootererRefreshing];
                    }
                } else {
                    [strongSelf setFootererRefreshing];
                }
                
            }
            [strongSelf reloadData:YES];
        });
    }];
}

/// 请求下一页数据
- (void)requestNextPageData
{
    [self stopRequest];
    self.currentPage++;
    __weak typeof(self) weakSelf = self;
    [self startRequestCompletion:^(NSArray *dataItems, NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            [strongSelf endRefreshing];
            if (error) {
                strongSelf.currentPage--;
                [strongSelf showErrorToast:error];
                return;
            }
            if (dataItems.count == 0) {
                strongSelf.currentPage--;
                [strongSelf endRefreshingWithNoMoreData];
                return;
            }
            
            if ([strongSelf isDataItemsMerged]) {
                if (strongSelf.dataItems.count == dataItems.count) {
                    strongSelf.currentPage--;
                    [strongSelf endRefreshingWithNoMoreData];
                }
                [strongSelf.dataItems removeAllObjects];
            }
            [strongSelf.dataItems addObjectsFromArray:dataItems];
            [strongSelf reloadData:(strongSelf.currentPage == 0)];
        });
    }];
}

- (void)reloadData:(BOOL)isFirstPage
{
    if (self.reloadDataBlock) {
        self.reloadDataBlock(isFirstPage);
    } else {
        [self reloadData];
    }
}

#pragma mark - KSListViewDelegate

- (void)setHeaderRefreshing
{
    if ([self.pagingListDelegate respondsToSelector:@selector(setHeaderRefreshingBlock:)]) {
        __weak typeof(self) weakSelf = self;
        [weakSelf.pagingListDelegate setHeaderRefreshingBlock:^{
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf requestFirstPageData];
        }];
    }
}

- (void)setFootererRefreshing
{
    if ([self.pagingListDelegate respondsToSelector:@selector(setFooterRefreshingBlock:)]) {
        __weak typeof(self) weakSelf = self;
        [weakSelf.pagingListDelegate setFooterRefreshingBlock:^{
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf requestNextPageData];
        }];
    }
}

- (void)endRefreshing
{
    if ([self.pagingListDelegate respondsToSelector:@selector(endRefreshing)]) {
        [self.pagingListDelegate endRefreshing];
    }
}

- (void)endRefreshingWithNoMoreData
{
    if ([self.pagingListDelegate respondsToSelector:@selector(endRefreshingWithNoMoreData)]) {
        [self.pagingListDelegate endRefreshingWithNoMoreData];
    }
}

- (void)showErrorView:(NSError *)error
{
    if ([self.pagingListDelegate respondsToSelector:@selector(showErrorView:setRetryBlock:)]) {
        __weak typeof(self) weakSelf = self;
        [weakSelf.pagingListDelegate showErrorView:error setRetryBlock:^{
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if (strongSelf) {
                [strongSelf requestFirstPageData];
            }
        }];
    }
}

- (void)hideErrorView
{
    if ([self.pagingListDelegate respondsToSelector:@selector(hideErrorView)]) {
        [self.pagingListDelegate hideErrorView];
    }
}

- (void)showErrorToast:(NSError *)error
{
    if ([self.pagingListDelegate respondsToSelector:@selector(showErrorToast:)]) {
        [self.pagingListDelegate showErrorToast:error];
    }
}

#pragma mark - KSListViewDataSource

- (void)startRequestCompletion:(void(^)(NSArray *dataItems, NSError *error))completion
{
    if ([self.pagingListDataSource respondsToSelector:@selector(startRequestCompletion:)]) {
        [self.pagingListDataSource startRequestCompletion:completion];
    }
}

- (void)stopRequest
{
    if ([self.pagingListDataSource respondsToSelector:@selector(stopRequest)]) {
        [self.pagingListDataSource stopRequest];
    }
}

- (void)setCurrentPage:(NSUInteger)currentPage
{
    _currentPage = currentPage;
    if ([self.pagingListDataSource respondsToSelector:@selector(setCurrentPage:)]) {
        [self.pagingListDataSource setCurrentPage:currentPage];
    }
}

- (NSUInteger)pageSize
{
    if ([self.pagingListDataSource respondsToSelector:@selector(pageSize)]) {
        return [self.pagingListDataSource pageSize];
    } else {
        return 10;
    }
}

- (BOOL)isDataItemsMerged
{
    if ([self.pagingListDataSource respondsToSelector:@selector(isDataItemsMerged)]) {
        return [self.pagingListDataSource isDataItemsMerged];
    }
    return NO;
}

- (void)saveFirstPageDataToCache
{
    if ([self.pagingListDataSource respondsToSelector:@selector(saveFirstPageDataToCache)]) {
        [self.pagingListDataSource saveFirstPageDataToCache];
    }
}

- (NSArray *)firstPageDataCache
{
    if ([self.pagingListDataSource respondsToSelector:@selector(firstPageDataCache)]) {
        return [self.pagingListDataSource firstPageDataCache];
    }
    return nil;
}

@end
